import Vue from 'vue'
import Router from 'vue-router'
import { MessageBox } from 'element-ui';
import store from '@/store/'


Vue.use(Router)


const router = new Router({
    routes: [
        {
            path: '/',
            name: 'root',
            redirect: '/login',
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/login'),
        },
        // ...getRoutes(routeArr),     //导航菜单相关的路由
        // {
        //   path: '*',
        //   redirect: '/login'
        // }
    ]
})

//进入页面之前token验证
router.beforeEach((to, from, next) => {
    //先检查token，校验登录状态
    if (to.path !== '/login') {
        if (!sessionStorage.getItem('token')) {
            if (to.path === '/') {
                next('/login')
            } else {
                MessageBox.alert('请重新登录', {
                    confirmButtonText: '确定',
                    type: 'warning',
                    callback: () => {
                        next('/login')
                    }
                })
            }
        } else {
            //页面刷新的情况下，导航数据被清空，此时需要重新请求
            if (store.state.menus.length === 0) {
                store.dispatch('getMenu').then(() => {
                    //hack方法，router.addRoutes之后的next()可能会失效，因为可能next()的时候路由并没有完全add完成
                    next({ ...to, replace: true })
                })
            } else {
                next()
            }
        }
    } else {
        next()
    }
})

export default router
